package cn.kgc.controller;

import cn.kgc.pojo.AppCategory;
import cn.kgc.pojo.AppInfo;
import cn.kgc.pojo.AppVersion;
import cn.kgc.pojo.DataDictionary;
import cn.kgc.service.Gl_AppInfoService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mysql.jdbc.StringUtils;
import org.apache.commons.io.FilenameUtils;

import org.apache.commons.lang3.RandomUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.HashMap;
import java.util.List;


/**
 * @author:
 * @date: 2022/1/4
 * @description:
 */
@Controller
@RequestMapping("/info")
public class Gl_AppInfoController {

    //获得日志类对象
    Logger logger = Logger.getLogger(Gl_AppInfoController.class);

    //将service层作为属性自动装配到当前bean
    @Resource
    private Gl_AppInfoService glservice;


///*
//*
//     * 通过超链接跳转到此方法，转到添加页面
//     * @return
//
//    @RequestMapping("/add")
//    public String Add() {
//        return "developer/appinfoadd";
//    }
//*/


    /**
     * 通过添加页面的表单提交，post方式跳转到此方法，进行添加操作
     */
    @PostMapping("/save")
    public String addInfo(AppInfo appInfo, HttpServletRequest request,
                          @RequestParam(value = "a_logoPicPath", required = false) MultipartFile attach) {

    //1、定义保存到数据库的图片路径
        String picPath = null;

        //2、原文件路径
        String path = null;

        //3、文件名称
        String fileName = null;
        System.out.println(appInfo.getSoftwareName());
        System.out.println(appInfo.getSupportROM());
        System.out.println(appInfo.getSoftwareSize());
        System.out.println(appInfo.getDownloads());
        System.out.println(appInfo.getStatus());
        System.out.println(appInfo.getCategoryLevel1());
        System.out.println(appInfo.getCategoryLevel2());
        System.out.println(appInfo.getCategoryLevel3());
        System.out.println(appInfo.getFlatformId());
        System.out.println(appInfo.getAppInfo());
        System.out.println(appInfo.getLogoLocPath());
        System.out.println(appInfo.getLogoPicPath());
    //4、如果文件不为空
        if (!attach.isEmpty()) {
            //5、获得文件源路径
            path = request.getSession().getServletContext().getRealPath("statics" + File.separator + "upload");
            logger.info("uploadFile path ============== > " + path);

            //6、获得原文件名
            String oldFileName = attach.getOriginalFilename();
            logger.info("uploadFile oldFileName ============== > " + oldFileName);

            //7、获得原文件后缀
            String prefix = FilenameUtils.getExtension(oldFileName);
            logger.debug("uploadFile prefix============> " + prefix);

            //8、设置文件大小5000k,就是5mb
            int filesize = 5000000;
            logger.debug("uploadFile size============> " + attach.getSize());

            //9、如果源文件大小超过设定值
            if (attach.getSize() > filesize) {
                //10、进行文件过大提示
                request.setAttribute("uploadFileError", " * 上传大小不得超过 5mb");
                //11、返回添加页面
                return "developer/appinfoadd";

                //12、如果文件格式(忽略大小写的后缀)是apk格式
            } else if (prefix.equalsIgnoreCase("jpg")||prefix.equalsIgnoreCase("png")) {
                //13、给文件重命名为       当前系统的毫秒数+四位随机数 + .apk后缀
                fileName = System.currentTimeMillis() + RandomUtils.nextInt() + ".jpg";
                logger.debug("new fileName======== " + attach.getName());

                File targetFile = new File(path, fileName);
                //14、如果文件不存在,就生成此文件
                if (!targetFile.exists()) {
                    targetFile.mkdirs();
                }
                //15、保存
                logger.debug("---------------fileName=" + fileName);

                try {
                    //16、保存文件
                    attach.transferTo(targetFile);
                } catch (Exception e) {
                    e.printStackTrace();
                    request.setAttribute("uploadFileError", " * 上传失败！");
                    return "developer/appinfoadd";
                }
                picPath = path + File.separator + fileName;
            } else {
                request.setAttribute("uploadFileError", " * 上传图片格式不正确");
                return "developer/appinfoadd";
            }
        }
        //17、获得源文件路径(下载地址)  新文件路径 赋值给对象的对应属性
        appInfo.setLogoLocPath(path);
        appInfo.setLogoPicPath(picPath);



        boolean bo= glservice.add(appInfo);

        logger.debug(bo);

        if (bo) {
            logger.debug("添加成功！"); //跳转到查询版本页面
            return "redirect:/info/appinfoadd";
        }else{
            logger.debug("添加失败！"); //跳转到查询版本页面
            request.setAttribute("uploadFileError", " * 上传失败！");
            return "developer/appinfoadd";
        }


    }

//    @RequestMapping("/add")
//    public String add(){
//        return "/developer/appinfolist";}
    /**
     * 增加app信息（跳转到新增appinfo页面）
     * @param appInfo
     * @return
     */
    @RequestMapping(value="/appinfoadd",method=RequestMethod.GET)
    public String add(@ModelAttribute("appInfo") AppInfo appInfo){
        return "developer/appinfoadd";
    }




    /**
     * 判断APKName是否唯一
     * @param
     * @return
     */
    @RequestMapping(value="/apkexist.json",method=RequestMethod.GET)
    @ResponseBody
    public Object apkNameIsExit(@RequestParam String APKName){
        HashMap<String, String> resultMap = new HashMap<String, String>();
        if(StringUtils.isNullOrEmpty(APKName)){
            resultMap.put("APKName", "empty");
        }else{
            AppInfo appInfo = null;
            try {
                appInfo = glservice.getAppInfo(null, APKName);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            if(null != appInfo)
                resultMap.put("APKName", "exist");
            else
                resultMap.put("APKName", "noexist");
        }
        return JSONArray.toJSONString(resultMap);
    }


    public List<DataDictionary> getDataDictionaryList(String typeCode){
        List<DataDictionary> dataDictionaryList = null;
        try {
            dataDictionaryList = glservice.getDataDictionaryList(typeCode);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return dataDictionaryList;
    }

    /**
     * 根据typeCode查询出相应的数据字典列表
     * @param
     * @return
     */
    @RequestMapping(value="/datadictionarylist.json",method=RequestMethod.GET)
    @ResponseBody
    public String getDataDicList (@RequestParam String tcode){
        logger.debug("getDataDicList tcode ============ " + tcode);
        String str=JSONObject.toJSONString(getDataDictionaryList(tcode));
        System.out.println("下面是乱码！！！！！！！！！！！！！！！");
        System.out.println(str);
        return str;
    }


    /**
     * 根据parentId查询出相应的分类级别列表
     * @param pid
     * @return
     */
    @RequestMapping(value="/categorylevellist.json",method=RequestMethod.GET)
    @ResponseBody
    public String getAppCategoryList (@RequestParam String pid){
        logger.debug("getAppCategoryList pid ============ " + pid);
        if(pid.equals("")) pid = null;
        return JSONObject.toJSONString(getCategoryList(pid));
    }

    public List<AppCategory> getCategoryList (String pid){
        List<AppCategory> categoryLevelList = null;
        try {
            categoryLevelList = glservice.getAppCategoryListByParentId(pid==null?null:Integer.parseInt(pid));
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return categoryLevelList;
    }
    /**
     * 查看app信息，包括app基本信息和版本信息列表（跳转到查看页面）
     * @param
     * @return
     */
    @RequestMapping(value="/appview/{id}",method=RequestMethod.GET)
    public String view(@PathVariable String id,Model model){
        AppInfo appInfo = null;
        List<AppVersion> appVersionList = null;
        try {
            appInfo = glservice.getAppInfo(Integer.parseInt(id),null);
            appVersionList = glservice.getAppVersionList(Integer.parseInt(id));
        }catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        model.addAttribute("appVersionList", appVersionList);
        model.addAttribute(appInfo);
        return "developer/appinfoview";
    }

}


